package com.hp.bon.sgw.ctrl;

import java.util.LinkedHashMap;
import java.util.Map;

import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.hp.bon.sgw.util.ProcessCaller;

/**
 * 采用本地调用的第三方API库，实现的跨平台的系统信息调用类
 * 
 * @author wuzhih
 * 
 */
public class SystemPlantformJNIImpl implements SystemPlantformIntf {

	private Sigar sigar = new Sigar();
	private static final Logger logger = LoggerFactory.getLogger(SystemPlantformJNIImpl.class);

	@Override
	public double getCpuUsage() {
		double value = 0;
		try {
			value = sigar.getCpuPerc().getCombined();
			if (Double.isNaN(value)) {
				value = 0;
				logger.warn("current CPU value is NaN");
			}
		} catch (SigarException e) {
			logger.warn("Could not fetch current CPU value," + e.toString());
		}
		return value;
	}

	@Override
	public double getMemUsage() {
		double value = 0;
		try {
			value = sigar.getMem().getUsedPercent() / 100;
			if (Double.isNaN(value)) {
				value = 0;
				logger.warn("current Mem value is NaN");
			}
		} catch (SigarException e) {
			logger.warn("Could not fetch current Mem value," + e.toString());
		}
		return value;
	}

	@Override
	public long[] checkProcessExists(String[] progsPattern) throws Exception {
		long[] results = new long[progsPattern.length];
		long[] pids = sigar.getProcList();
		Map<Long, String> processLst = new LinkedHashMap<Long, String>();
		for (long pid : pids) {
			try {
				String[] cmdArgs = sigar.getProcArgs(pid);
				StringBuilder cmdLine = new StringBuilder();
				for (String arg : cmdArgs) {
					cmdLine.append(arg).append(" ");
				}
				processLst.put(pid, cmdLine.toString());
			} catch (SigarException e) {

			}
		}

		int i = 0;
		for (String progPtn : progsPattern) {
			for (Map.Entry<Long, String> entry : processLst.entrySet()) {
				String process = entry.getValue();
				if (process.contains(progPtn)) {
					results[i] = entry.getKey();
					break;
				}
			}
			i++;
		}
		return results;
	}

	@Override
	public boolean shutdownProcess(long pid) throws Exception {
		sigar.kill(pid, "TERM");
		return true;
	}

	@Override
	public boolean startProcess(String[] cmdAndParams) throws Exception {
		ProcessCaller caller = new ProcessCaller();
		caller.startProgram(cmdAndParams);
		// startedProcesse.add(caller);
		return true;
	}

	public void shutdown() {
		sigar.close();
	}
}
